package com.zst.demo3.controller;

import com.zsr.entities.CommonResult;
import com.zsr.entities.PermissionDTO;
import com.zsr.entities.RoleDTO;
import com.zst.demo3.po.RolePermissionPO;
import com.zst.demo3.service.Demo4FeignService;
import com.zst.demo3.service.IRolePermissionService;
import com.zst.demo3.service.IRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@RestController
@RequestMapping("/zst/demo3")
@Slf4j
public class IndexController {

    @Resource
    Demo4FeignService demo4FeignService;

    @Autowired
    IRoleService iRoleService;

    @Autowired
    IRolePermissionService iRolePermissionService;

    @GetMapping("/index")
    public String index() {
        log.info("this is demo3 application.");
        return "this is demo3 application.";
    }

    @GetMapping("/get-role/{id}")
    public CommonResult<RoleDTO> getRole(@PathVariable("id") Long id) {
        // 调用角色信息
        Optional<RoleDTO> roleDTOOpt = iRoleService.getRoleById(id);
        if (!roleDTOOpt.isPresent()) {
            return CommonResult.ResultSuccess(null);
        }
        RoleDTO roleDTO = roleDTOOpt.get();
        if(Objects.isNull(roleDTO.getId())){
            return CommonResult.ResultSuccess(null);
        }
        // 获取permissionId
        Optional<List<RolePermissionPO>> rolePermissionListOpt = iRolePermissionService.getRolePermissionById(id);
        if (!rolePermissionListOpt.isPresent()) {
            return CommonResult.ResultSuccess(roleDTO);
        }
        // 循环调用
        rolePermissionListOpt.get().forEach(s -> {
            // 获取permission
            CommonResult<PermissionDTO> permission = demo4FeignService.getPermission(s.getRoleId());
            if (Objects.nonNull(permission.getData())) {
                roleDTO.getPermissionList().add(permission.getData());
            }
        });
        return CommonResult.ResultSuccess(roleDTO);
    }
}
